package yl.hs.bmipfull.service.salemanage.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.salemanage.ICustomerUserDao;
import yl.hs.bmipfull.daos.salemanage.ILinkerInfoDao;
import yl.hs.bmipfull.pojo.salemanage.CustomerInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.CustomerUserEntity;
import yl.hs.bmipfull.pojo.salemanage.LinkerInfoEntity;
import yl.hs.bmipfull.security.MD5;
import yl.hs.bmipfull.service.salemanage.ILinkerInfoService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.util.*;

/**
* 作用:  联系人服务层接口实现<br/>
* 创建时间: 2021年05月19日 11时16分38秒 <br/>
* @author 谢东
*/
@Service
public class LinkerInfoServiceImpl extends SaleBaseService implements ILinkerInfoService  {

    @Autowired
    ILinkerInfoDao dao;
    @Autowired
    ICustomerUserDao customerUserDao;
    @Autowired
    ILinkerInfoDao linkdao;
    @Override
    public List<LinkerInfoEntity> queryList(PageQuery pageQuery) throws Exception{
        pageQuery.checkSortSides(LinkerInfoEntity.class);
        return dao.queryList(pageQuery.getQuery());
    }
    @Override
    public PageResult<Map<String,Object>> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(LinkerInfoEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<Map<String,Object>> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),LinkerInfoEntity.class);

        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(),getTagSNs(),filters));
        result.setPage(page);
        String[] str=getTagSNs();
        var data = dao.queryPage(pageQuery.getQuery(),str,filters);
        var nData = new ArrayList<Map<String,Object>>();
        if(data.size()>0) {
            var linkerSNList = data.stream().map(t -> t.getSn()).toList();
            var users = cUserDao.queryByLinerSnAndType(linkerSNList, Tl.getDBMapCode(CustomerInfoEntity.class));
            for (var link:data){
                var item = link.toMap();
                var userOpt = users.stream().filter(t->t.getLinkerSN().equals(link.getSn())).findFirst();
                var linkType=-1;
                if(!userOpt.isEmpty()){
                    linkType = userOpt.get().getLinkType();
                }
                item.put("Link_Role",linkType);
                nData.add(item);
            }
        }
        result.setData(nData);
        return result;
    }



    @Override
    public LinkerInfoEntity findBySn(String sn){
         return dao.findBySN(sn);
     }

    @Override
    @Transactional
    public Integer saveLinkerInfo(Map<String,Object> model,String sn) throws Exception{
        Integer result;
        var CurrentUser=HsApp.getCurrent();
        if (Tl.isEmpty(sn)) {
            //执行保存
            LinkerInfoEntity entity = new LinkerInfoEntity();
            Tl.getChangeLog(entity, model);
            var linkentity = linkdao.findUserByAccount(entity.getMobilePhone());
            if(linkentity!=null){
                return -1;
            }
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(LinkerInfoEntity.class));
            var linker=dao.findBySN(CurrentUser.getUserSN());
            if(linker!=null){
                entity.setCustSn(linker.getCustSn());
                entity.setCustomerName(linker.getCustomerName());
            }
            if (entity.getBirthday() == null) {entity.setBirthday(new Date());}
            entity.setAge((short) (Tl.getYearDifference(new Date(),entity.getBirthday())));
            if (entity.getCustType()==null){
                entity.setCustType((short) 1);
            }
            entity.setPassword("031272DA4FEDA089FA51245D574F04C4");//默认密码：0000
            entity.setRealPassword("4A7D1ED414474E4033AC29CCB8653D9B");//默认密码：0000
            result = dao.insertNew(entity);
            //客户系统用户 linkType
            if(Tl.getShort(model.get("Link_Role"),(short) -1)>-1){
                var user = new CustomerUserEntity();
                user.setSn(queryNewSN(user.getClass()));
                user.setLinkerSN(entity.getSn());
                user.setLinkType(Tl.getShort(model.get("Link_Role")));
                user.setObjSN(entity.getCustSn());
                user.setObjType(Tl.getDBMapCode(CustomerInfoEntity.class));
                cUserDao.insertNew(user);
            }

            if (result > 0) {
               var shareCode =  writeUserTag(entity.getSn(),entity.getClass(), RelationType.CREATE.toString());
                saveGS(
                        entity.getSn(),
                        entity.getFullName(),
                        String.join(",",
                                entity.getFullName(),
                                entity.getCustomerName(),
                                entity.getBentInfo(),
                                entity.getCompanyName(),
                                entity.getDepartment(),
                                entity.getPosition(),
                                entity.getLinkFrom(),
                                entity.getMobilePhone(),
                                entity.getQq(),
                                entity.getEmail(),
                                entity.getWechat(),
                                entity.getSupplierName()
                        ),
                        entity,
                        HsApp.getCurrent()!=null?HsApp.getCurrent().getUserSN():null,
                        shareCode
                );
                writeLog(ActionType.CREATE, entity.getSn(), "插入联系人信息", Tl.toJson(entity), LinkerInfoEntity.class);
            }

        } else {
            //执行修改
            var entity = findBySn(sn);
            var backJson = entity.toJson();

            var linkentity = linkdao.findUserByAccount(model.get("mobilePhone").toString());
            if(linkentity!=null && !entity.getMobilePhone().equals(linkentity.getMobilePhone())){
                return -1;
            }
            var changeLog = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            if (entity.getBirthday() == null) {entity.setBirthday(new Date());}
            entity.setAge((short) (Tl.getYearDifference(new Date(),entity.getBirthday())));
            if (entity.getCustType()==null){
                entity.setCustType((short) 1);
            }
            entity.setPassword(entity.getPassword());
            entity.setRealPassword(entity.getRealPassword());
            result = dao.update(entity);
            //客户系统用户 linkType
            if(Tl.getShort(model.get("Link_Role"),(short) -1)>-1){
                var cUser=cUserDao.findByCustSNAndLinkSN(entity.getSn(), entity.getCustSn());
                if(cUser!=null){
                    cUser.setLinkerSN(entity.getSn());
                    cUser.setLinkType(Tl.getShort(model.get("Link_Role")));
                    cUser.setObjSN(entity.getCustSn());
                    cUser.setObjType(Tl.getDBMapCode(CustomerInfoEntity.class));
                    cUserDao.update(cUser);
                }else{
                    var user = new CustomerUserEntity();
                    user.setSn(queryNewSN(user.getClass()));
                    user.setLinkerSN(entity.getSn());
                    user.setLinkType(Tl.getShort(model.get("Link_Role")));
                    user.setObjSN(entity.getCustSn());
                    user.setObjType(Tl.getDBMapCode(CustomerInfoEntity.class));
                    cUserDao.insertNew(user);
                }

            }
            if (result > 0) {
                saveGS(
                        entity.getSn(),
                        entity.getFullName(),
                        String.join(",",
                                entity.getFullName(),
                                entity.getCustomerName(),
                                entity.getBentInfo(),
                                entity.getCompanyName(),
                                entity.getDepartment(),
                                entity.getPosition(),
                                entity.getLinkFrom(),
                                entity.getMobilePhone(),
                                entity.getQq(),
                                entity.getEmail(),
                                entity.getWechat(),
                                entity.getSupplierName()
                        ),
                        entity,
                        HsApp.getCurrent()!=null?HsApp.getCurrent().getUserSN():null,
                        null
                );
                writeLog(ActionType.UPDATE, sn, changeLog, backJson, LinkerInfoEntity.class);
            }
        }

        return result;
     }

    @Override
    public Integer updatePWD(String sn, String oldPassword, String password) {
        var entity=dao.findBySN(sn);
        if(entity.getPassword().equals(MD5.getMD5(oldPassword))){
            entity.setPassword(MD5.getMD5(password));
            entity.setRealPassword(password);
            return dao.update(entity);
        }else{
            return -1;
        }
    }

    @Override
    public Integer delete(String[] sn) {
        var result = dao.changeStateBySn(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, LinkerInfoEntity.class);
            deleteGs(sn);
        }
        return result;
    }

    @Override
    public List<LinkerInfoEntity> queryListByCustomerSN(String customerSN) {
        return dao.queryListByCustomerSN(customerSN);
    }

    @Override
    public Integer changeStateBySn(String[] snArray,short state) {
        int result=dao.changeStateBySn(snArray,state);
        if (result > 0) {
            forWriteLog(snArray,state);
        }
        return result;
    }

    @Override
    public CustomerUserEntity findCustomUser(String linkerSN, String customSN) {
        return cUserDao.findByCustSNAndLinkSN(linkerSN,customSN);
    }

    @Override
    public LinkerInfoEntity findByOpenId(String openid) {
        return dao.getByOpenid(openid);
    }

    @Autowired
    ICustomerUserDao cUserDao;
}